<template>
  <div class="inventory-detail detail-bg">
    <div class="header">
      <h5>盘点详情({{ taskNum }}, {{ getStatusText(inventoryTaskDetail?.status) }})</h5>
      <el-button @click="goBack" type="text" class="back-btn">
        <i class="el-icon-arrow-left"></i> 返回
      </el-button>
    </div>
    
    <!-- 基本信息 -->
    <el-card class="info-card" shadow="never">
      <el-row :gutter="20">
        <el-col :span="8">
          <div class="info-item">
            <span class="label">盘点任务名称：</span>
            <span class="value">{{ inventoryTaskDetail?.taskName || '-' }}</span>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="info-item">
            <span class="label">盘点仓库：</span>
            <span class="value">{{ inventoryTaskDetail?.stockName || '-' }}</span>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="info-item">
            <span class="label">盘点库区：</span>
            <span class="value">{{ getWarehouseNames() || '-' }}</span>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="info-item">
            <span class="label">盘点日期：</span>
            <span class="value">{{ formatDate(inventoryTaskDetail?.takeDate) || '-' }}</span>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="info-item">
            <span class="label">盘点人：</span>
            <span class="value">{{ inventoryTaskDetail?.userName || '-' }}</span>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="info-item">
            <span class="label">盘点备注：</span>
            <span class="value">{{ inventoryTaskDetail?.note || '-' }}</span>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 盘点明细 -->
    <el-card class="detail-card" shadow="never" style="margin-top: 20px;">
      <template #header>
        <span class="card-header">盘点物品(共{{count}})
          <el-button type="primary" size="small" @click="switchToList" style="margin-left: 10px;">切换列表展示</el-button>
        </span>
      </template>
      
      <el-collapse v-if="inventoryTaskDetail?.warehouseList && inventoryTaskDetail.warehouseList.length > 0">
        <el-collapse-item 
          v-for="(warehouse, warehouseIdx) in inventoryTaskDetail.warehouseList" 
          :key="warehouseIdx" 
          :title="`${warehouse.name}（共${warehouse.taskNum || 0}项，已完成${warehouse.finishedNum || 0}，未完成${warehouse.unfinishedNum || 0}）`"
        >
          <div v-for="(location, locationIdx) in (warehouse.locationDTOList || [])" :key="locationIdx" style="margin-bottom: 16px;">
            <el-collapse>
              <el-collapse-item 
                :title="`${location.location}（共${location.taskNum || 0}项，已完成${location.finishedNum || 0}，未完成${location.unfinishedNum || 0}）`" 
                :name="`${warehouseIdx}-${locationIdx}`"
              >
                <el-table 
                  :data="location.taskDetailDTOList || []" 
                  border 
                  size="small" 
                  style="margin: 8px 0;"
                  :empty-text="'该货位暂无盘点物品'"
                >
                  <el-table-column label="序号" type="index" width="50" />
                  <el-table-column prop="code" label="物品编码" width="120" />
                  <el-table-column prop="category" label="物品品类" width="100" />
                  <el-table-column prop="name" label="物品名称" width="150" />
                  <el-table-column prop="spec" label="物品规格" width="120" />
                  <el-table-column prop="unit" label="计量单位" width="80" />
                  <el-table-column prop="batchNo" label="批次号" width="120" />
                  <el-table-column prop="validTime" label="有效期" width="120" />
                  <el-table-column prop="locationName" label="货位" width="100" />
                  <el-table-column prop="systemQty" label="库存数量" width="90" />
                  <el-table-column prop="actualQty" label="实盘数量" width="90" />
                  <el-table-column prop="diffQty" label="盘亏/盘盈" width="100">
                    <template #default="scope">
                      <span 
                        :style="{
                          color: scope.row.diffQty > 0 ? '#67c23a' : (scope.row.diffQty < 0 ? '#f56c6c' : '#606266'),
                          fontWeight: scope.row.diffQty !== 0 ? 'bold' : 'normal'
                        }"
                      >
                        {{ scope.row.diffQty !== null && scope.row.diffQty !== undefined ? scope.row.diffQty : '-' }}
                      </span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="breakage" label="报损数量" width="100">
                    <template #default="scope">
                      {{ scope.row.breakage || 0 }}
                    </template>
                  </el-table-column>
                </el-table>
              </el-collapse-item>
            </el-collapse>
          </div>
        </el-collapse-item>
      </el-collapse>
      
      <el-empty v-else description="暂无盘点明细数据" />
    </el-card>
    <el-button 
      v-if="inventoryTaskDetail?.status !== 4 && inventoryTaskDetail?.status !== 5" 
      style="margin-top: 16px;" 
      @click="updateNumGroup"
    >
      修改实盘数量
    </el-button>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getTaskDetailByGroup, getcountTaskDetail } from '@/api/Inventory/taskDetailGroup';

const position = ref('left')
const inventoryTaskDetail = ref({});
const route = useRoute();
const router = useRouter();
const taskNum = ref('');
const count = ref(0);

// 格式化日期
function formatDate(timestamp) {
  if (!timestamp) return '-';
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}`;
}

// 获取状态文本
function getStatusText(status) {
  const statusMap = {
    1: '待盘点',
    2: '盘点中',
    3: '待调整',
    4: '已完成',
    5: '已作废'
  };
  return statusMap[status] || '-';
}

// 获取库区名称列表
function getWarehouseNames() {
  if (!inventoryTaskDetail.value?.warehouseList || inventoryTaskDetail.value.warehouseList.length === 0) {
    return '-';
  }
  return inventoryTaskDetail.value.warehouseList.map(warehouse => warehouse.name).join('、');
}

// 返回上一页
function goBack() {
  history.back();
}

// 获取盘点任务详情
async function init() {
  try {
    const res = await getTaskDetailByGroup(taskNum.value);
    if (res.code == 200) {
      inventoryTaskDetail.value = res.data;
    } else {
      ElMessage.error('获取盘点任务详情失败：' + res.msg);
    }
  } catch (error) {
    ElMessage.error('获取盘点任务详情失败：' + error.message);
  }
}

// 获取盘点任务物品总数
async function countGoods() {
    const res = await getcountTaskDetail(taskNum.value);
    if (res.code == 200) {
      count.value = res.data;
  }
}

// 切换到列表展示
function switchToList() {
  router.push({ name: '盘点任务详情(列表展示)', query: { code: taskNum.value } });
}

function updateNumGroup(){
  router.push({ name: '修改盘点数量(分组)',query: { code: taskNum.value } });
}
// 获取路由参数
onMounted(() => {
  const code = route.query.code;
  if (code) {
    taskNum.value = code;
    init();
    countGoods();
  }
});
</script>

<style scoped>
.el-row {
  margin-bottom: 20px;
}
.el-row:last-child {
  margin-bottom: 0;
}
.el-col {
  border-radius: 4px;
}

.grid-content {
  border-radius: 4px;
  min-height: 20px;
}
.detail-bg {
  background: #fff;
  min-height: 100vh;
  width: 100vw;
  margin: 0;
  padding: 0 0 32px 0;
  box-sizing: border-box;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.back-btn {
  font-size: 14px;
  color: #409eff;
}

.info-card {
  margin-bottom: 20px;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.label {
  font-size: 14px;
  color: #606266;
  margin-right: 10px;
}

.value {
  font-size: 14px;
  color: #303133;
  font-weight: bold;
}

.detail-card {
  margin-top: 20px;
}

.card-header {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}
</style>